#define __USE_GNU
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include "builtin.h"

int setenv(const char *nombre, const char *valor, int sobrescribir);
char *get_current_dir_name(void);

int my_cd (const char * path)
{

	char * cwd = NULL;
	char * ncwd = NULL;
	char * home = NULL;
	int err = 0;

	cwd = get_current_dir_name ();

	if (path == NULL) /**debo llevarlo al HOME */
	{
		home = getenv ("HOME");
		if (home != NULL)
		{
			err = chdir (home);
			if (err == 0)
			{
				setenv ("OLDPWD", cwd, 1);
				setenv ("PWD", home, 1);
			}
		}
		
	}
	else
	{
		err = chdir (path);
		if (err == 0)
		{
			ncwd = get_current_dir_name ();
			setenv ("OLDPWD", cwd, 1);
			setenv ("PWD", ncwd, 1);
			free (ncwd);
			ncwd = NULL;
		}
	}

	free (cwd);
	cwd = NULL;
	
	return err;
}

void salir (void)
{
	exit (0);
}

bool es_interno (const scommand * scmd)
{

	const_bstring aux = NULL;
	bool b = false;
	bstring name = NULL;

	assert (scmd != NULL);

	aux = scommand_front (scmd);
	name = bstrcpy (aux);
	if ( (biseqcstr (name, "cd")) || (biseqcstr (name, "exit")) )
		b = true;

	/*bdestroy (aux);*/
	bdestroy (name);
	return b;
}
	